<?php

//设置时区
date_default_timezone_set('Asia/Shanghai');

require 'webapp/webapp_stdio.php';
require 'models/redis.php';
require 'models/base.php';
require 'models/proxy.php';
require 'models/user.php';
require 'models/task.php';

//CLI 执行方式 php home.php get?home/action
class webapp_router_home extends webapp_echo_json
{


    function err(string $msg = '', int $code = 400)
    {
        $this['msg'] = $msg;
        $this['code'] = $code;
        return 200;
    }
    function succ(string|array|int $data)
    {
        $this['data'] = $data;
        $this['code'] = 200;
        return 200;
    }

    function get_task(int $num = 1,int $uid = 0)
    {
       
        $this['data'] = $this->webapp->task->get(min(10, max($num, 1)),$uid);
        // return $this->err('系统功能未开发完成，待开发完后再使用');
    }

    function post_back_task()
    {
        $taskDetailId = $this->webapp->request_content()['task_detail_id'] ?? 0;
        $this->webapp->task->back($taskDetailId) ? $this->succ('success') : $this->err('失败');
    }

    function post_proxy_update()
    {
        $this->webapp->proxy->updateUserProxy(
            intval($this->webapp->request_content()['user_id'] ?? 0),
            intval($this->webapp->request_content()['proxy_id'] ?? 0),
            intval($this->webapp->request_content()['proxy_type'] ?? 0),
        )
            ? $this->succ('标记代理不可用：成功')
            : $this->err('标记代理不可用：失败');
    }

    function post_note_update()
    {
        $taskId = intval($this->webapp->request_content()['task_id'] ?? 0);
        $status = trim($this->webapp->request_content()['status'] ?? '');

        if ($taskId <= 0) return $this->err('参数错误');
        if (!in_array($status, ['timeout', 'notfound'])) return $this->err('参数错误');

        $this->webapp->task->update($taskId, ['status' => $status]) ? $this->succ('success') : $this->err('更新笔记失败');
    }


    function post_task_detail_update()
    {
        $taskDtId = intval($this->webapp->request_content()['id'] ?? 0);
        $status = trim($this->webapp->request_content()['status'] ?? '');

        if (!in_array($status, ['success', 'failed'])) {
            return  $this->err('更新子任务参数错误');
        }

        $this->webapp->task->updateTaskDetail($taskDtId, ['execution_status' => $status]) ? $this->succ('success') : $this->err('更新子任务失败');
    }

    function post_user_update()
    {
        $userId = intval($this->webapp->request_content()['id'] ?? 0);
        $status = trim($this->webapp->request_content()['status'] ?? '');
        //当前只开放relogin
        if ($status != 'relogin' && $status != 'nocomment') {
            return $this->err('更新用户失败');
        }
        $this->webapp->user->update($userId, ['status' => $status]) ? $this->succ('success') : $this->err('更新用户失败');
    }
    function post_user_login()
    {
        $form = $this->webapp->request_content();
        $uid = $this->webapp->user->login($form);
        return $uid > 0 ? $this->succ($uid) : $this->err('登录失败,资料有误');
    }


    function post_task_update() {}

    function get_home()
    {
        $this->webapp->user->updateFingerPrint();
        $this->webapp->user->updateCity();
        // $this['proxy'] = $this->webapp->proxy->get(2);
    }

    function get_test()
    {
        $this['proxy'] = $this->webapp->proxy->get(2);
    }

    function get_user(int $uid){
        $this['data'] = $this->webapp->user->getUserNoTask($uid);
    }


    // 自动保存执行情况
    // */10 * * * * cd /jaychou/redbook && php home.php get?home/auto-save
    function get_auto_save()
    {
        //判断cli模式
        if (php_sapi_name() != "cli") {
            return $this->err('仅支持CLI模式');
        }

        $this['data'] = $this->webapp->user->saveExecuteInfo();

        return $this->succ('success');
    }

    // 分配任务超过5分钟未执行的任务，全部重新排队
    // */5 * * * * cd /jaychou/redbook && php home.php get?home/auto-back
    function get_auto_back()
    {
        //判断cli模式
        if (php_sapi_name() != "cli") {
            return $this->err('仅支持CLI模式');
        }
        // ($this->webapp->mysql)("UPDATE task_detail SET `execution_status` = 'pending',excute_at = DATE_ADD(excute_at, INTERVAL 600 SECOND) WHERE deleted_at is null AND `execution_status` = 'running' AND TIMESTAMPDIFF(SECOND, push_at, NOW()) > 600");
        $this->webapp->task->backTimeoutTask();

        return $this->succ('success');        
    }
    function get_auto_fuck(string $hash){
        echo $hash,"\n";
        $this->webapp->task->optimizeTaskExecuteTime($hash);
        echo "OK\n";
    }

     
}


new class extends webapp
{
    public $rds, $user, $task, $proxy;
    function __construct()
    {
        $config = require('local.config.php');
        parent::__construct($config['webapp']);
        $this->rds = RedisManager::getInstance($config['redis']);
        $this->user = new User($this);
        $this->task = new Task($this);
        $this->proxy = new Proxy($this);
    }
};
